import { Button, Input, Tooltip, message, Spin } from "antd";
import { PictureOutlined, LoadingOutlined, BulbOutlined, ThunderboltOutlined, DeleteOutlined, HomeOutlined } from "@ant-design/icons";
import { useEffect, useState } from "react";
import { useStorage } from "@plasmohq/storage/hook";
import WallpaperModal from "./components/wallpaper-modal";
import QuoteCard from "./components/quote-card";
import styles from "./index.module.scss";
import ClockTime from "./components/clock-time"

export default function Popup() {
    const [currentUrl, setCurrentUrl] = useState("");
    const [loading, setLoading] = useState(true);
    const [wallpaperModalVisible, setWallpaperModalVisible] = useState(false);
    const [wallpaper, setWallpaper] = useStorage<string>("wallpaper")
    const [minimalMode, setMinimalMode] = useStorage("minimal-mode", false);

    // 切换极简模式
    const toggleMinimalMode = () => {
        setMinimalMode(!minimalMode);
    };

    // 获取当前标签页 URL
    useEffect(() => {
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            if (tabs[0]?.url) {
                setCurrentUrl(tabs[0].url);
            } else {
                setCurrentUrl("无法获取当前网页URL");
            }
            setLoading(false);
        });
    }, []);

    // 应用壁纸到插件界面
    useEffect(() => {
        if (!wallpaper) return

        const isVideo = wallpaper.endsWith(".mp4")

        // 清理之前的壁纸元素
        const oldBg = document.getElementById("extension-wallpaper")
        if (oldBg) oldBg.remove()

        if (isVideo) {
            const video = document.createElement("video")
            video.id = "extension-wallpaper"
            video.src = wallpaper
            video.autoplay = true
            video.loop = true
            video.muted = true
            video.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100vw;
                height: 100vh;
                object-fit: cover;
                z-index: -1;
            `
            document.body.appendChild(video)
        } else {
            const div = document.createElement("div")
            div.id = "extension-wallpaper"
            div.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100vw;
                height: 100vh;
                background: url(${wallpaper}) center/cover no-repeat;
                z-index: -1;
            `
            document.body.appendChild(div)
        }
    }, [wallpaper])

    // 初始化背景
    useEffect(() => {
        if (!wallpaper) {
            initWallpaper();
            // document.body.style.backgroundColor = "#000";
        }
    }, []);

    // 万能解析跳转
    const handleJump = () => {
        if (!currentUrl || currentUrl === "无法获取当前网页URL") {
            message.error("无法获取有效URL");
            return;
        }

        try {
            const urlObj = new URL(currentUrl);
            const pathUrl = `${urlObj.hostname}${urlObj.pathname}${urlObj.search}`;
            const finalUrl = `https://wn.run/${pathUrl}`;
            window.open(finalUrl, "_blank", "noopener,noreferrer");
            message.success(`正在跳转到: ${finalUrl}`);
        } catch (error) {
            message.error(`URL格式错误: ${error.message}`);
        }
    };

    // 选择壁纸回调
    const handleWallpaperSelect = async (url: string) => {
        setWallpaper(url)
        setWallpaperModalVisible(false)

        // 保存到本地存储
        await setWallpaper(url)
        // 通知background更新所有标签页
        chrome.runtime.sendMessage({ 
            type: "UPDATE_WALLPAPER", 
            url 
        }).catch(console.error)
        message.success("壁纸已应用到所有活动标签页")
    }

    const clearStorage = () => { 
        // 清空浏览器壁纸缓存
        chrome.runtime.sendMessage({ 
            type: "DELETE_WALLPAPER", 
        }).catch(console.error)
        // 清理设置的壁纸元素
        const oldBg = document.getElementById("extension-wallpaper")
        if (oldBg) {
            // oldBg.remove()  //移除所有壁纸
            // 更改为默认壁纸
            initWallpaper();
            message.success("已恢复默认壁纸")
        } else {
            message.info("暂未设置壁纸")
        }
    }

    // 初始化壁纸
    const initWallpaper = () => { 
        const video = document.createElement("video")
        video.id = "extension-wallpaper"
        video.src = "https://files.codelife.cc/itab/defaultWallpaper/videos/63.mp4"
        video.autoplay = true
        video.loop = true
        video.muted = true
        video.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            object-fit: cover;
            z-index: -1;
        `
        document.body.appendChild(video)
    }



    return (
        <div className={styles.popupContainer}>
            {/* 极简模式切换按钮（右上角） */}
            <div className={styles.minimalToggle}>
                <Tooltip title={minimalMode ? "退出极简模式" : "进入极简模式"}>
                    <Button
                        type="text"
                        icon={<BulbOutlined />}
                        style={{color:'white'}}
                        onClick={toggleMinimalMode}
                    />
                </Tooltip>
            </div>
            {/* 极简模式只显示时钟 */}
            {minimalMode ? (
                <div className={styles.clockWrapper}>
                    <ClockTime />
                </div>
            ) : (
                <div
                    style={{
                        width: 360,
                        height: "100%",
                        padding: 20,
                        textAlign: "center",
                        margin: 0,
                        display: "flex",
                        flexDirection: "column",
                        gap: 16,
                    }}
                >
                    <ClockTime />
                    <Input
                        placeholder="可输入要跳转的网址或者搜索关键字"
                        value={currentUrl}
                        onChange={(e) => setCurrentUrl(e.target.value)}
                        allowClear
                        style={{ width: "100%",backgroundColor: "rgba(255, 255, 255, 0.6)"  }}
                        disabled={loading}
                        suffix={loading ? <LoadingOutlined /> : null}
                    />

                    <div className={styles.buttonGroup}>
                        <Tooltip title="获取该网页在线工具，包含视频解析、网站翻译、网页截图等" color="rgba(0,0,0,0.6)" placement="topRight">
                            <Button 
                                style={{backgroundColor: "rgba(255, 255, 255, 0.6)",}}
                                icon={<ThunderboltOutlined />}
                                onClick={handleJump}
                                className={styles.actionBtn}>
                                万能解析
                            </Button>
                        </Tooltip>

                        <Button
                            style={{backgroundColor: "rgba(255, 255, 255, 0.6)",}}
                            icon={<PictureOutlined />}
                            onClick={() => setWallpaperModalVisible(true)}
                            className={styles.actionBtn}
                        >
                            更换壁纸
                        </Button>

                        <Button
                            style={{backgroundColor: "rgba(255, 255, 255, 0.6)",}}
                            icon={<HomeOutlined />}
                            className={styles.actionBtn}
                            onClick={() => {
                                chrome.tabs.create({ url: './options.html' });
                            }}
                        >
                            主页
                        </Button>

                        <Button
                            style={{backgroundColor: "rgba(255, 255, 255, 0.6)",}}
                            icon={<DeleteOutlined />}
                            className={styles.actionBtn}
                            onClick={() => clearStorage() }
                        >
                            重置壁纸
                        </Button>
                    </div>

                    {/* 壁纸选择弹窗 */}
                    <WallpaperModal
                        visible={wallpaperModalVisible}
                        onClose={() => setWallpaperModalVisible(false)}
                        onSelect={handleWallpaperSelect}
                    />
                    {/* 每日一言 */}
                    <QuoteCard />

                </div>
            )}
        </div>
    );
}